import Vue from 'vue'
import Panel from './panel.vue'

const PanelConstructor = Vue.extend(Panel)

export default Vue => {
  let panelInstanceCache = {}
  const OneMapPanel = {
    open: function (options) {
      //判断是否已经存在
      const has = Object.keys(panelInstanceCache).includes(options.key)
      if (has) {
        console.log(`${options.key}已存在`)
        return
      }
      const panelInstance = new PanelConstructor({
        data: options.data,
        propsData: {
          panelKey: options.key
        },
        components: {
          'panel-component': options.component
        }
      })
      const vm = panelInstance.$mount()
      const dom = vm.$el
      document.body.appendChild(dom)
      panelInstanceCache[options.key] = panelInstance
      panelInstance.$on('closed', () => {
        delete panelInstanceCache[options.key]
        if (options.closed) {
          options.closed()
        }
      })
      return panelInstance
    },
    // 销毁单个
    destory: function (key) {
			console.log('destory', panelInstanceCache[key].$el)
      if (!panelInstanceCache[key]) {
        return
      }
      panelInstanceCache[key].destory()
			// document.body.removeChild(panelInstanceCache[key].$el) // 也可以使用这行代码
      delete panelInstanceCache[key]
    },
    // 销毁所有
    destoryAll: function () {
      Object.keys(panelInstanceCache).map(key => {
        panelInstanceCache[key].destory()
      })
      panelInstanceCache = {}
    },
    // 获取组件实例
    getCompVm(key) {
      if (!panelInstanceCache[key]) {
        return
      }
      return panelInstanceCache[key].compVm
    }
  }
  Vue.prototype.$OneMapPanel = OneMapPanel
}
